import { reqGetCartList, deleteGood, reqCheckCart } from '@/api'
import { getUUID } from '@/utils/uuId_token'

const state = {
  cartList: [],
  uuId_token: getUUID()
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  async getCartList({ commit }) {
    const res = await reqGetCartList()
    if (res.code == 200) {
      commit('GETCARTLIST', res.data)
    }
  },
  async deleteGood({ commit }, skuId) {
    const res = await deleteGood(skuId)
    if (res.code == 200) {
      return 'ok'
    }
    return Promise.reject(Error('删除商品失败!'))
  },
  // 切换商品选择状态
  async changeCartChecked({ commit }, { skuID, isChecked }) {
    const res = await reqCheckCart(skuID, isChecked)
    if (res.code == 200) {
      return ''
    } else {
      return Promise.reject(Error('切换商品状态失败!'))
    }
  },
  // 切换全选状态
  updateCheckAll({ dispatch, state }, isChecked) {
    state.cartList[0].cartInfoList.forEach((item) => {
      item.isChecked = isChecked
      dispatch('changeCartChecked', { skuID: item.skuId, isChecked })
    })
  }
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
